﻿using DiyEFConfigurationBuilder.Obersver;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DiyEFConfigurationBuilder
{
    internal class DiyEFContext : DbContext
    {
        public DiyEFContext(DbContextOptions<DiyEFContext> options) : base(options)
        { 
        
        }


        public DbSet<DiyConfig> DiyConfigs { get; set; }

        public override int SaveChanges()
        {
            TrackEntityChanges();
            return base.SaveChanges();
        }
        public async Task<int> SaveChangesAsync()
        {
            TrackEntityChanges();
            return await base.SaveChangesAsync();
        }

        /// <summary>
        /// 实体监控
        /// </summary>
        private void TrackEntityChanges()
        {
            foreach (var entry in ChangeTracker.Entries().Where(e =>
                e.State == EntityState.Modified || e.State == EntityState.Added || e.State == EntityState.Deleted))
            {
                if (entry.Entity.GetType().Equals(typeof(DiyConfig)))
                {
                    EntityChangeObserver.Instance.OnChanged(new EntityChangeEventArgs(entry));
                }
                return;
            }
        }
    }
}
